package br.com.consultsystems.persistencia.impl.financeiro;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.consultsystems.dominio.financeiro.Historico;
import br.com.consultsystems.dominio.tipos.TipoHistorico;
import br.com.consultsystems.persistencia.spec.AbstractAdministradoraRepository;
import br.com.consultsystems.persistencia.spec.financeiro.HistoricoPersistencia;

@Stateless(name = "historicoPersistencia")
public class HistoricoPersistenciaImpl extends
		AbstractAdministradoraRepository<Historico> implements
		HistoricoPersistencia {

	protected HistoricoPersistenciaImpl() {
		super(Historico.class);
	}

	@Override
	public List<Historico> retrieveAll() {
		return retrieveByCriteria(null);
	}

	@Override
	public List<Historico> retrieveByFilter(String descricao) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Historico> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Historico> root = createRoot(criteriaQuery);
		
		/* Repository -> Apenas pesquias as informações no banco de dados
		 * Filtro por codigo */
		final Path<String> pathDescricao = root.get("descricao");
		final Predicate predicateDescricao = criteriaBuilder.like(pathDescricao, "%"+descricao+"%");
		criteriaQuery.where(predicateDescricao);
		criteriaQuery.orderBy(criteriaBuilder.asc(pathDescricao));
		
		final TypedQuery<Historico> typedQuery = em.createQuery(criteriaQuery);
		
		return typedQuery.getResultList();
	}

	@Override
	public List<Historico> retrieveByFilter(String descricao,
			TipoHistorico tipoHistorico) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Historico> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Historico> root = createRoot(criteriaQuery);

		final Path<TipoHistorico> pathTipoHistorico = root.get("tipo");
		final Predicate predicateTipoHistorico = criteriaBuilder.equal(pathTipoHistorico, tipoHistorico);
		
		final Path<String> pathDescricao = root.get("descricao");
		final Predicate predicateDescricao = criteriaBuilder.like(pathDescricao, "%"+descricao+"%");
		
		criteriaQuery.where(predicateTipoHistorico, predicateDescricao);
		criteriaQuery.orderBy(criteriaBuilder.asc(pathDescricao));
		
		final TypedQuery<Historico> typedQuery = em.createQuery(criteriaQuery);
		
		return typedQuery.getResultList();
	}

}
